<?php
/**
 * Created by PhpStorm.
 * User: Nph
 * Date: 2017/5/30
 * Time: 13:29
 */

namespace apps\api\modules\user\controllers;


use common\modules\site\Region;
use xing\article\map\ArticleMap;
use common\modules\site\logic\SmsLogic;
use common\modules\site\logic\RegionLogic;
use common\modules\article\Article;
use common\modules\task\map\TaskMap;
use common\modules\task\service\TaskProgressService;
use common\modules\user\logic\UserLogic;
use common\modules\user\map\UserMap;
use common\modules\user\User;
use common\modules\user\UserFollow;
use xing\helper\exception\ApiCodeException;
use common\map\api\ResponseMap;
use Yii;

class UserController extends \apps\api\modules\ApiBaseController
{

    public $checkLogin = false;
    public $modelClass = 'common\modules\user\User';

    public function actionCheckNickname($nickname)
    {

        try {
            $isExist = User::find()->where(['nickname' => $nickname])->exists();
            return $this->returnData(['isExist' => $isExist]);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    /**
     * 获取手机验证码
     * @return array
     */
    public function actionGetMobileCode()
    {
        $mobile = Yii::$app->request->post('mobile');
        try {

            UserLogic::checkMobile($mobile);
            if (User::existsMobile($mobile)) throw new \Exception('手机已被注册');
            SmsLogic::sendTextCode($mobile);
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }


    /**
     * 注册
     * @return array|mixed
     * @throws \Throwable
     */
    public function actionRegister()
    {
        $mobile = $email = Yii::$app->request->post('mobile');
        $password = Yii::$app->request->post('password');
        $mobileCode = Yii::$app->request->post('code');
        $recommendUserId = Yii::$app->request->post('recommendUserId');


        try {
            UserLogic::checkMobileCode($mobile, $mobileCode);
            $user = UserLogic::register($mobile, $password, $recommendUserId);
            # 删除验证码
            SmsLogic::clearCode($mobile);

            return $this->returnData($user);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    /**
     * 登陆
     * @return array
     */
    public function actionLogin()
    {
        $mobile = Yii::$app->request->post('mobile');
        $driveCode = Yii::$app->request->post('driveCode');
        $password = Yii::$app->request->post('password');
        $loginMobileModel = Yii::$app->request->post('loginMobileModel');
        $loginMobileVendor = Yii::$app->request->post('loginMobileVendor');
//        er(md5($mobile . $password . $driveCode . $time . CommonMap::APP_YUN_SECRET));

        try {
            $user = UserLogic::appLogin($mobile, $password, $driveCode, $loginMobileModel, $loginMobileVendor);

            return $this->returnData(UserLogic::apiFormat($user));
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

//    是否登陆
    public function actionHasLogin()
    {
        $userId = Yii::$app->request->post('loginUserId');
        $token = Yii::$app->request->post('loginToken');
        $r = TokenUserService::checkToken($userId, $token);
        return $this->returnData(['hasLogin' => $r ? '1' : '0']);
    }

    public function actionGetLoveInformation()
    {

        $userId = intval(Yii::$app->request->post('loginUserId'));

        if (!empty($this->user)) {
            $return = [
                'hasLogin' => 1,
                'newFriendApply' => LoveFriendApply::find()->where(['userId' => $userId, 'isRead' => 0])->exists(),
                'newQuestionnaire' => LoveQuestionnaireSet::readLastSet($userId)->newAttendNumber ?? 0,
                'newVisit' => LoveUserBrowse::find()->where(['toUserId' => $userId, 'isRead' => 0])->exists(),
                'newFollow' => LoveUserFollow::find()->where(['followUserId' => $userId, 'isRead' => 0])->exists(),
            ];
        } else {
            $return = ['hasLogin' => 0];
        }
        return $this->returnData($return);
    }

    /**
     * @param $userId
     * @return array|mixed
     */
    public function actionView($userId)
    {
            $data = User::logicFindOne($userId);
            if (empty($data)) throw new \Exception('没有这个用户');
            $return = $data->toArray();
            unset($return['password_hash'], $return['password_reset_token'], $return['loginToken'], $return['mobile']);
            $return['myFollow'] = UserFollow::countMyFollow($userId);
            $return['followMy'] = UserFollow::countFollowMy($userId);
            $return['isFollow'] = UserFollow::readInfo($this->userId, $userId) ? 1 : 0;
			$return['cityName'] = Region::readFullName($this->user->cityId);
            $return['countArticle'] = Article::find()->where(['userId' => $this->userId, 'status' => ArticleMap::STATUS_SHOW])->count();

        try {
            return $this->returnData($return);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 修改我的资料
     * @return array
     */
    public function actionUpdate()
    {
        try {
            $this->checkLogin();
            $m = User::findOne($this->userId);
            foreach (['nickname', 'avatar', 'say', 'sex', 'bkog', 'cityId'] as $key) {
                isset($_POST[$key]) && $m->$key = $_POST[$key];
            }
            $m->logicSave();
            TaskProgressService::finishTaskOnce($this->userId, TaskMap::CODE_UPDATE_USER);
            return $this->returnData($m);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 忘记密码
     * @return array
     */
    public function actionForgotPassword()
    {
        $mobile = $email = Yii::$app->request->post('mobile');
        $passwordMd5 = Yii::$app->request->post('password');
        $mobileCode = Yii::$app->request->post('code');
        try {
            UserLogic::checkMobileCode($mobile, $mobileCode);
            UserLogic::updatePassword($mobile, $passwordMd5);
            # 删除验证码
            SmsLogic::clearCode($mobile);
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionLogout()
    {
        try {
            parent::checkLogin();
            User::logout($this->userId);
            return $this->returnApiSuccess();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function actionSearch($q, $page = 1)
    {

        try {
            $list = User::getModel($page)->where(['like', 'nickname', $q])->all();
            return $this->returnList($list);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }
}